#!/usr/bin/env python

# There should be two parameters passed into this script, StartTime timestamp and EndTime timestamp for generating
#   custom graph, need to return the location and topic of each graph to Django

import os
import sys
import rrdtool
import time

from utils import snmp_query


class RrdGraph:

    def __init__(self, start_time='-1d', end_time='now'):
        if start_time == '-1d':
            start_timestamp = int(time.time() - 86400)
        else:
            start_timestamp = int(time.mktime(time.strptime(end_time, '%m/%d/%Y')))
        if end_time == 'now':
            start_time = int(time.time())
        else:
            end_timestamp = int(time.mktime(time.strptime(start_time, '%m/%d/%Y')))
        self.filepath = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), 'netgraph/static/img')
        self.start = start_time
        self.end = end_time
        self.query = snmp_query.QueryOidData('127.0.0.1', 'public')
        self.prefixf = str(start_timestamp) + '-' + str(end_timestamp)
        self.xgrid = "MINUTE:10:HOUR:1:HOUR:1:0:%H"

    def cpu_graph(self):
        graph_file = self.prefixf + '_cpu_util.png'
        graph_title = 'CPU Utilization Graph'
        graph_file_path = os.path.join(self.filepath, graph_file)
        rrd_db_path = os.path.join(self.filepath, 'cpu_util.rrd')
        rrd_def = "DEF:cpuutil=%s:cpu_util:AVERAGE" % rrd_db_path
        rrdtool.graph(graph_file_path, "--start", self.start, "--end", self.end, "--vertical-label=%",
                      "--x-grid", "MINUTE:10:HOUR:1:HOUR:1:0:%H",
                      "--width", "380", "--height", "120", "--title", graph_title,
                      rrd_def,
                      "AREA:cpuutil#00FF00:CPU Utilization",
                      "GPRINT:cpuutil:AVERAGE:CPU Utilization [avg=%3.2lf",
                      "GPRINT:cpuutil:MAX:max=%3.2lf",
                      "GPRINT:cpuutil:MIN:min=%3.2lf]\\r"
                      )
        return {graph_title: graph_file}

    def interface_graph(self):
        if_names = self.query.ifnames
        traffic = {}
        for if_name in if_names:
            rrd_db = if_name + '.rrd'
            graph_file = self.prefixf + '_' + if_name + '.png'
            graph_file_path = os.path.join(self.filepath, graph_file)
            rrd_defin = "DEF:inoctets=%s:in:AVERAGE" % os.path.join(self.filepath, rrd_db)
            rrd_defout = "DEF:outoctets=%s:out:AVERAGE" % os.path.join(self.filepath, rrd_db)
            graph_title = "%s Traffic Graph" % if_name
            rrdtool.graph(graph_file_path, "--start", self.start, "--end", self.end, "--vertical-label=Bytes/s",
                          "--x-grid", "MINUTE:10:HOUR:1:HOUR:1:0:%H",
                          "--width", "380", "--height", "120", "--title", graph_title,
                          rrd_defin,
                          rrd_defout,
                          "AREA:inoctets#00FF00:In Traffic",
                          "LINE1:outoctets#0000FF:Out Traffic\\r",
                          "CDEF:inbits=inoctets,8,*",
                          "CDEF:outbits=outoctets,8,*",
                          "COMMENT:\\r",
                          "GPRINT:inbits:AVERAGE:Traffic In [avg=%3.2lf%S",
                          "GPRINT:inbits:MAX:max=%3.2lf%S",
                          "GPRINT:inbits:MIN:min=%3.2lf%S]\\r",
                          "GPRINT:outbits:AVERAGE:Traffic Out [avg=%3.2lf%S",
                          "GPRINT:outbits:MAX:max=%3.2lf%S",
                          "GPRINT:outbits:MIN:min=%3.2lf%S]\\r"
                          )
            traffic[graph_title] = graph_file
        return traffic

    def run(self):
        data = {}
        cpu = self.cpu_graph()
        traffic = self.interface_graph()
        data.update(cpu)
        data.update(traffic)
        return data
